package com.jingzhi.huimiao;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.StrictMode;
import android.util.Log;
import android.view.Window;
import android.widget.Toast;

import cn.smssdk.SMSSDK;

import com.google.gson.Gson;
import com.jingzhi.huimiao.bean.User;
import com.jingzhi.huimiao.bean.User.WrongWord;
import com.jingzhi.huimiao.utils.CanstantUtils;
import com.jingzhi.huimiao.utils.ConnectionDetector;
import com.jingzhi.huimiao.utils.DataStoreUtil;
import com.jingzhi.huimiao.utils.DensityUtil;
import com.jingzhi.huimiao.utils.HttpUtils;
import com.jingzhi.huimiao.utils.SQLdm;

public class SplashActivity extends Activity {

	public static final int WHAT = 0;
	private Long stime;
	private String currentime;
	private int year;
	private int month;
	private int day;
	private String time;

	Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 0:
				Boolean hasInMain = DataStoreUtil.getBoolean(
						SplashActivity.this, "hasInMain");
				if (hasInMain) {
					// 鍦ㄨ繘鍏ヤ富椤甸潰鍓嶉渶瀹屾垚鐨勪簨鎯�
					beforeToMain();

					startActivity(new Intent(SplashActivity.this,
							MainActivity.class));
				} else {
					startActivity(new Intent(SplashActivity.this,
							GuideActivity.class));
				}
				finish();
				break;

			default:
				break;
			}
		}

	};

	private SQLiteDatabase db;
	private Cursor rightcur;
	private int rightcount;
	private int currentRC;
	private Cursor wrongcur;
	private String responseData;
	private HttpURLConnection conn;
	private String smonth;
	private String sday;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_splash);

		SQLdm s = new SQLdm();
		db = s.openDatabase(SplashActivity.this);

		
		
		int px1 = DensityUtil.px2dip(getApplication(), 38);
		int px2 = DensityUtil.px2dip(getApplication(), 76);
//		Log.e("TAG------PX1---PX2---", px1 + "----" + px2);
		handler.sendEmptyMessageDelayed(WHAT, 1000);
	}

	/**
	 * 1.璁＄畻鎵撳崱鏃堕棿 2.鍒ゆ柇鏄惁鑱旂綉 3.鏈仈缃戝垯鎻愮ず锛岃仈缃戝垯涓庢湇鍔″櫒鍚屾鐢ㄦ埛鏁版嵁
	 */
	private void beforeToMain() {
		// TODO Auto-generated method stub

		// 缁熻鎵撳崱鏃堕棿
		stime = DataStoreUtil.getLong(SplashActivity.this, "studytime");//鎵撳崱娆℃暟
		currentime = DataStoreUtil.getString(SplashActivity.this, "currentime");//鎵撳崱鏃堕棿

		Calendar c = Calendar.getInstance();
		year = c.get(Calendar.YEAR);
		month = c.get(Calendar.MONTH) + 1;
		if(month<10){
			smonth = "0"+month;
		}else{
			smonth = month+"";
		}
		int day = c.get(Calendar.DAY_OF_MONTH);
		if(day<10){
			sday = "0"+day;
		}else{
			sday = day+"";
		}
		time = year + smonth + sday;

//		Log.e("TIME", time);

		if (stime == null) {
			stime = (long) 1;
		} else if (time.equals(currentime)) {

			Toast.makeText(SplashActivity.this, "浠婃棩宸茬粡鎵撹繃鍗′簡鍝�....", 0).show();
		} else {
			DataStoreUtil.put(SplashActivity.this, "currentime", time);
			stime++;
		}

		DataStoreUtil.putint(SplashActivity.this, "studytime", stime);

		// 鍒ゆ柇鏄惁鑱旂綉
		ConnectionDetector cd = new ConnectionDetector(SplashActivity.this);
		if (cd.isConnectingToInternet()) {
			// 鑱旂綉鎴愬姛
			Toast.makeText(SplashActivity.this, "鑱旂綉鎴愬姛", 0).show();

			// 浼犺緭鏁版嵁
			sendData();
		} else {
			// 鑱旂綉澶辫触
			Toast.makeText(SplashActivity.this, "缃戠粶寮傚父銆傘�傘�傘��", 0).show();
		}
	}

	private void sendData() {
		// 鐢ㄤ簬鎹曡幏纾佺洏璁块棶鎴栬�呯綉缁滆闂腑涓庝富杩涚▼涔嬮棿浜や簰浜х敓鐨勯棶棰�
		StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
				.detectDiskReads().detectDiskWrites().detectNetwork()
				.penaltyLog().build());
		StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
				.detectLeakedSqlLiteObjects().detectLeakedClosableObjects()
				.penaltyLog().penaltyDeath().build());

		try {
			JSONObject UerKey = new JSONObject();

			long uid = DataStoreUtil.getLong(SplashActivity.this, "userid");
			UerKey.put("uid", uid);

			// 鏌ヨ琛ㄤ腑璇ョ敤鎴风殑姝ｇ‘绛斿鐨勫崟璇嶆暟锛屼篃灏辨槸缁忛獙鍊肩殑浜斿垎涔嬩竴
			rightcur = db.rawQuery("select * from word where word_right=2;",
					null);
			if (rightcur.moveToFirst()) {
				rightcount = rightcur.getCount();
			}
			// 鏌ヨsp涓瓨鍌ㄧ殑缁忛獙鍊�
			currentRC = DataStoreUtil
					.getInt(SplashActivity.this, "experience");
			if (currentRC < rightcount * 5) {
				currentRC = rightcount * 5;
			}

			UerKey.put("experience", currentRC);

			JSONArray array = new JSONArray();
			// 鏌ヨ鐢熻瘝鏈腑鏁版嵁
			wrongcur = db.rawQuery("select * from wrong_word where user_id="
					+ uid + "", null);
			while (wrongcur.moveToNext()) {
				
				JSONObject WrongKey = new JSONObject();
				long wordid = wrongcur.getLong(wrongcur
						.getColumnIndex("word_id"));
				String insertime = wrongcur.getString(wrongcur
						.getColumnIndex("insert_time"));
				WrongKey.put("userId", uid);
				WrongKey.put("wordId", wordid);
				WrongKey.put("inserTime", insertime);
				
				array.put(WrongKey);
			}

			UerKey.put("wrong_word", array);

			// 鎵撳崱淇℃伅
			long studytime = DataStoreUtil.getLong(SplashActivity.this,
					"studytime");
			UerKey.put("studytime", studytime);

			/* 灏佽Data瀵硅薄 */

			JSONObject params = new JSONObject();

			params.put("Data", UerKey);

			// 浼犺緭json鏁版嵁
			/* 鎶奐SON鏁版嵁杞崲鎴怱tring绫诲瀷浣跨敤杈撳嚭娴佸悜鏈嶅姟鍣ㄥ啓 */

			String content = String.valueOf(params);
			Log.e("CONTENT", params+"");

			URL url = new URL(CanstantUtils.splash_url);
			

			conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(5000);

			conn.setDoOutput(true);// 璁剧疆鍏佽杈撳嚭

			conn.setRequestMethod("POST");

			conn.setRequestProperty("User-Agent", "Fiddler");

			conn.setRequestProperty("Content-Type", "application/json");

			conn.setRequestProperty("Charset", "utf-8");

			OutputStream os = conn.getOutputStream();

			os.write(content.getBytes());
			os.close();

			/* 鏈嶅姟鍣ㄨ繑鍥炵殑鍝嶅簲鐮� */

			int code = conn.getResponseCode();
			Log.e("CONTENT", "----code-----"+code);

			if (code == 200)

			{

				BufferedReader in = new BufferedReader(new InputStreamReader(
						conn.getInputStream(), "UTF-8"));

				String retData = null;

				responseData = "";

				while ((retData = in.readLine()) != null)

				{

					responseData += retData;

				}

				Log.e("RESPONSEDATA", responseData);

				in.close();

				finish();

			}

			else

			{

				Toast.makeText(getApplicationContext(), "鏁版嵁鎻愪氦澶辫触",
						Toast.LENGTH_SHORT).show();

			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			if(wrongcur!=null){
				wrongcur.close();
			}
			if(rightcur!=null){
				rightcur.close();
			}
			if(db!=null){
				db.close();
			}
		}

	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		
		
	}
}
